package com.project.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.demo.entity.MeetingInformation;
import com.project.demo.service.MeetingInformationService;
import com.project.demo.service.CosService;
import com.project.demo.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Map;


/**
 * 会议信息：(MeetingInformation)表控制层
 *
 */
@Slf4j
@RestController
@RequestMapping("/meeting_information")
public class MeetingInformationController extends BaseController<MeetingInformation, MeetingInformationService> {

    /**
     * 会议信息对象
     */
    @Autowired
    public MeetingInformationController(MeetingInformationService service) {
        setService(service);
    }
    
    @Autowired
    private CosService cosService;

    @PostMapping("/add")
    @Transactional
    public Map<String, Object> add(HttpServletRequest request) throws IOException {
        Map<String,Object> paramMap = service.readBody(request.getReader());
        // 处理会议时间戳转换
        convertMeetingTime(paramMap);
        this.addMap(paramMap);
        return success(1);
    }
    
    @PostMapping("/set")
    @Transactional
    @Override
    public Map<String, Object> set(HttpServletRequest request) throws IOException {
        Map<String,Object> body = service.readBody(request.getReader());
        // 处理会议时间戳转换
        convertMeetingTime(body);
        service.update(service.readQuery(request), service.readConfig(request), body);
        return success(1);
    }
    
    /**
     * 转换会议时间戳为Timestamp对象
     * @param paramMap 参数Map
     */
    private void convertMeetingTime(Map<String, Object> paramMap) {
        if (paramMap != null && paramMap.containsKey("meeting_time")) {
            Object meetingTime = paramMap.get("meeting_time");
            if (meetingTime != null) {
                try {
                    Timestamp timestamp = null;
                    
                    // 如果已经是Timestamp类型，直接使用
                    if (meetingTime instanceof Timestamp) {
                        timestamp = (Timestamp) meetingTime;
                    }
                    // 如果是Long类型（时间戳）
                    else if (meetingTime instanceof Long) {
                        timestamp = new Timestamp((Long) meetingTime);
                    }
                    // 如果是Integer类型（时间戳）
                    else if (meetingTime instanceof Integer) {
                        timestamp = new Timestamp(((Integer) meetingTime).longValue());
                    }
                    // 如果是字符串
                    else if (meetingTime instanceof String) {
                        String timeStr = (String) meetingTime;
                        // 如果是纯数字字符串（时间戳）
                        if (timeStr.matches("^\\d+$")) {
                            timestamp = new Timestamp(Long.parseLong(timeStr));
                        }
                        // 如果是日期时间字符串格式（yyyy-MM-dd HH:mm:ss）
                        else if (timeStr.matches("^\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}:\\d{2}$")) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            timestamp = new Timestamp(sdf.parse(timeStr).getTime());
                        }
                        // 尝试直接解析
                        else {
                            try {
                                timestamp = Timestamp.valueOf(timeStr);
                            } catch (IllegalArgumentException e) {
                                log.warn("无法解析会议时间字符串: {}", timeStr);
                            }
                        }
                    }
                    
                    if (timestamp != null) {
                        paramMap.put("meeting_time", timestamp);
                        log.info("会议时间转换成功: {} -> {}", meetingTime, timestamp);
                    }
                } catch (Exception e) {
                    log.error("转换会议时间失败: {}", meetingTime, e);
                }
            }
        }
    }
    
    /**
     * 会议信息上传接口（支持会议封面和各单位logo上传）
     */
    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
        log.info("会议信息上传接口被调用");
        if (file.isEmpty()) {
            return error(30000, "没有选择文件");
        }
        try {
            // 使用腾讯云COS上传
            String fileUrl = cosService.uploadFile(file);
            
            log.info("会议信息文件上传成功，URL: {}", fileUrl);
            
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("url", fileUrl);
            return success(jsonObject);
        } catch (Exception e) {
            log.error("会议信息COS上传失败：{}", e.getMessage(), e);
            // 如果COS上传失败，尝试本地存储作为备用方案
            try {
                String userDir = System.getProperty("user.dir");
                String filePath;
                if (userDir.endsWith("server")) {
                    filePath = userDir + "\\target\\classes\\static\\upload\\";
                } else {
                    filePath = userDir + "\\server\\target\\classes\\static\\upload\\";
                }
                java.io.File targetDir = new java.io.File(filePath);
                if (!targetDir.exists() && !targetDir.isDirectory()) {
                    targetDir.mkdirs();
                }
                String fileName = file.getOriginalFilename();
                java.io.File dest = new java.io.File(filePath + fileName);
                file.transferTo(dest);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("url", "/api/upload/" + fileName);
                log.warn("会议信息COS上传失败，使用本地存储备用方案");
                return success(jsonObject);
            } catch (java.io.IOException ioException) {
                log.error("会议信息本地存储也失败：{}", ioException.getMessage(), ioException);
            }
        }
        return error(30000, "上传失败");
    }

}
